package com.whpost.service.service.stamp.h5;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.whpost.service.dao.wx.TWxTokenDao;
import com.whpost.service.entity.wx.TWxToken;
import com.whpost.service.tools.Sha1;
import com.whpost.service.tools.ToolBean;
import com.whpost.service.tools.WxTools;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class JsApi
{
	@Resource
	private WxTokenServiceImpl wxTokenService;
	@Resource
	private TWxTokenDao tWxTokenDao;
	@Resource
	private WxTools wxTools;


	public String GetApiTicket(String appid, String secret,Long wx_id)
    {
        String access_token = wxTokenService.getToken(appid,secret,"1",wx_id);
        String jsapi_ticket ="";
        jsapi_ticket = tWxTokenDao.getToken("3", ToolBean.getToday(),wx_id);;
        String httpResult = null;
        try
        {
	        if (!StringUtils.isEmpty(jsapi_ticket))
	        {
	        	ToolBean.info("查询到jsapi_ticket没有过期，直接返回："+jsapi_ticket);
	        	return jsapi_ticket;
	        }
	        ToolBean.info("查询到jsapi_ticket已经过期，需要重新发起get请求来获取！");
	        String turl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+access_token+"&type=jsapi";

			JSONObject jsonObject = wxTools.httpRequest(turl,"GET",null);
	        ToolBean.info("查询到jsapi_ticket已经过期，需要重新发起get请求来获取！获取到返回信息："+httpResult);
	        if (jsonObject.containsKey("errcode"))
			{
				ToolBean.info("jsapi_ticket获取失败，错误码："+jsonObject.getString("errcode"));
				jsapi_ticket = "";
			}
			else{

				jsapi_ticket = jsonObject.getString("ticket");
				String a = jsonObject.getString("expires_in");
				ToolBean.info("jsapi_ticket获取成功，token："+jsapi_ticket);
				String expires_in = jsonObject.getString("expires_in");
				ToolBean.info("jsapi_ticket获取成功，token："+jsapi_ticket+",准备保存...");
				tWxTokenDao.delToken("3",wx_id);
				tWxTokenDao.saveToken(jsapi_ticket,a,"3",ToolBean.getToday(),wx_id);
				ToolBean.info("jsapi_ticket获取成功，token："+jsapi_ticket+",保存成功！");
			}
	 	}
        catch (Exception e)
        {
        	ToolBean.info("获取jsapi_ticket发生错误！"+e.toString());
        	return jsapi_ticket;
        }
        return jsapi_ticket;
	}
	public String GetJsSignature(String noncestr,String timestamp,String url,String ticket)
	{
		String signature="";
        String str = "jsapi_ticket="+ticket+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+url+"";
        signature = Sha1.encode(str);
		return signature;
	}
 }